"""
缓存管理器
用于管理 API 数据缓存，减少频繁爬取
"""

import json
import os
from datetime import datetime, timedelta
from typing import Optional, Dict, Any

class CacheManager:
    def __init__(self, cache_dir: str = None):
        """
        初始化缓存管理器
        
        Args:
            cache_dir: 缓存目录路径，如果为 None 则使用配置中的目录
        """
        if cache_dir is None:
            from config import CACHE_DIR
            cache_dir = CACHE_DIR
        
        self.cache_dir = cache_dir
        if not os.path.exists(cache_dir):
            os.makedirs(cache_dir)
    
    def _get_cache_file(self, key: str) -> str:
        """获取缓存文件路径"""
        return os.path.join(self.cache_dir, f"{key}.json")
    
    def get(self, key: str, max_age_hours: int = 4) -> Optional[Dict[str, Any]]:
        """
        获取缓存数据
        
        Args:
            key: 缓存键
            max_age_hours: 最大缓存时长（小时）
        
        Returns:
            缓存数据，如果不存在或已过期则返回 None
        """
        cache_file = self._get_cache_file(key)
        
        if not os.path.exists(cache_file):
            return None
        
        try:
            with open(cache_file, 'r', encoding='utf-8') as f:
                cache_data = json.load(f)
            
            # 检查缓存时间
            cached_at = datetime.fromisoformat(cache_data.get('cached_at'))
            max_age = timedelta(hours=max_age_hours)
            
            if datetime.now() - cached_at > max_age:
                print(f"缓存已过期: {key}")
                return None
            
            print(f"使用缓存: {key} (缓存于 {cached_at})")
            return cache_data
            
        except Exception as e:
            print(f"读取缓存失败: {e}")
            return None
    
    def set(self, key: str, data: Any) -> bool:
        """
        设置缓存数据
        
        Args:
            key: 缓存键
            data: 要缓存的数据
        
        Returns:
            是否成功
        """
        cache_file = self._get_cache_file(key)
        
        try:
            cache_data = {
                'data': data,
                'cached_at': datetime.now().isoformat(),
            }
            
            with open(cache_file, 'w', encoding='utf-8') as f:
                json.dump(cache_data, f, ensure_ascii=False, indent=2)
            
            print(f"缓存已更新: {key}")
            return True
            
        except Exception as e:
            print(f"写入缓存失败: {e}")
            return False
    
    def clear(self, key: str) -> bool:
        """
        清除指定缓存
        
        Args:
            key: 缓存键
        
        Returns:
            是否成功
        """
        cache_file = self._get_cache_file(key)
        
        try:
            if os.path.exists(cache_file):
                os.remove(cache_file)
                print(f"缓存已清除: {key}")
            return True
        except Exception as e:
            print(f"清除缓存失败: {e}")
            return False
    
    def clear_all(self) -> bool:
        """
        清除所有缓存
        
        Returns:
            是否成功
        """
        try:
            for filename in os.listdir(self.cache_dir):
                if filename.endswith('.json'):
                    os.remove(os.path.join(self.cache_dir, filename))
            print("所有缓存已清除")
            return True
        except Exception as e:
            print(f"清除所有缓存失败: {e}")
            return False

